package com.chzu.dao;

import com.chzu.utils.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.nutz.dao.*;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.dao.util.Daos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;

public class ObjectCtl {
    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectCtl.class);
    public ObjectCtl() {
    }

    public <T> T addT(Dao dao, T t) {
        try {
            T rt = dao.insert(t);
            return rt;
        } catch (Exception var5) {
            var5.printStackTrace();
            return null;
        }
    }

    public <T> boolean add(Dao dao, T t) {
        boolean rt = true;

        try {
            dao.insert(t);
            return rt;
        } catch (Exception var5) {
            var5.printStackTrace();
            return false;
        }
    }

    public <T> boolean update(Dao dao, T t) {
        return dao.updateIgnoreNull(t) == 1;
    }

    public <T> boolean update(Dao dao, Class<T> obj, Chain chain, Condition condition) {
        return dao.update(obj, chain, condition) > 0;
    }

    public <T> boolean updateSortRow(Dao dao, String tableName, String[] ids, String rowName, int initvalue) {
        try {
            for(int i = 0; i < ids.length; ++i) {
                Sql sql = Sqls.create("update " + tableName + " set " + rowName + "=" + (i + initvalue) + " where id=" + ids[i]);
                dao.execute(sql);
            }

            return true;
        } catch (Exception var8) {
            var8.printStackTrace();
            return false;
        }
    }

    public <T> boolean exeUpdateBySql(Dao dao, Sql sql) throws Exception {
        try {
            dao.execute(sql);
            return true;
        } catch (Exception var4) {
            throw var4;
        }
    }

    public <T> T detailById(Dao dao, Class<T> obj, int id) {
        try {
            T t = dao.fetch(obj, (long)id);
            return t;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public <T> T detailById(Dao dao, Class<T> obj, long id) {
        try {
            T t = dao.fetch(obj, id);
            return t;
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    public <T> T detailByName(Dao dao, Class<T> obj, String id) {
        try {
            T t = dao.fetch(obj, id);
            return t;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public <T> T detailByName(Dao dao, Class<T> obj, String colname, String name) {
        try {
            T t = dao.fetch(obj, Cnd.where(colname, "=", name));
            return t;
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    public <T> T detailByName(Dao dao, Class<T> obj, String colname, int name) {
        try {
            T t = dao.fetch(obj, Cnd.where(colname, "=", name));
            return t;
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    public <T> T detailByCnd(Dao dao, Class<T> obj, Condition cnd) {
        try {
            T t = dao.fetch(obj, cnd);
            return t;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public <T> T detailBySql(Dao dao, Class<T> obj, Sql sql) {
        try {
            Entity<T> entity = dao.getEntity(obj);
            sql.setEntity(entity);
            sql.setCallback(Sqls.callback.entity());
            dao.execute(sql);
            return sql.getObject(obj);
        } catch (Exception var5) {
            var5.printStackTrace();
            return null;
        }
    }

    public <T> boolean deleteById(Dao dao, Class<T> obj, int id) {
        return dao.delete(obj, (long)id) == 1;
    }

    public <T> boolean deleteById(Dao dao, Class<T> obj, long id) {
        return dao.delete(obj, id) == 1;
    }

    public <T> boolean deleteByIds(Dao dao, Class<T> obj, String[] ids) {
        boolean result = false;

        for(int i = 0; i < ids.length; ++i) {
            result = dao.delete(obj, (long) Integer.parseInt(StringUtils.null2String(ids[i]))) == 1;
        }

        return result;
    }

    public <T> boolean deleteByIdsLong(Dao dao, Class<T> obj, String[] ids) {
        boolean result = false;

        for(int i = 0; i < ids.length; ++i) {
            result = dao.delete(obj, Long.parseLong(StringUtils.null2String(ids[i]))) == 1;
        }

        return result;
    }

    public <T> boolean deleteByName(Dao dao, Class<T> obj, String name) {
        return dao.delete(obj, name) == 1;
    }

    public <T> boolean deleteByNames(Dao dao, Class<T> obj, String[] ids) {
        boolean result = false;

        for(int i = 0; i < ids.length; ++i) {
            result = dao.delete(obj, StringUtils.null2String(ids[i])) == 1;
        }

        return result;
    }

    public void delete(Dao dao, String table, Condition cnd) {
        dao.clear(table, cnd);
    }

    public <T> int getRowCount(Dao dao, Class<T> obj) {
        return dao.count(obj);
    }

    public <T> int getRowCount(Dao dao, Class<T> obj, Condition cnd) {
        return dao.count(obj, cnd);
    }

    public <T> int getIntRowValue(Dao dao, Sql sql) {
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                return rs.next() ? rs.getInt(1) : 0;
            }
        });
        dao.execute(sql);
        return sql.getInt();
    }

    public <T> List<T> list(Dao dao, Class<T> obj, Condition cnd) {
        try {
            List<T> t = dao.query(obj, cnd, (Pager)null);
            return t;
        } catch (Exception var6) {
            var6.printStackTrace();
            return null;
        }
    }

    public <T> List<T> list(Dao dao, Class<T> obj, Sql sql) {
        Entity<T> entity = dao.getEntity(obj);
        sql.setEntity(entity);
        sql.setCallback(Sqls.callback.entities());
        dao.execute(sql);
        return sql.getList(obj);
    }

    public <T> List<Map> list(Dao dao, Sql sql) {
        sql.setCallback(Sqls.callback.records());
        dao.execute(sql);
        return sql.getList(Map.class);
    }

    public <T> QueryResult listPage(Dao dao, Class<T> obj, int curPage, int pageSize, Condition cnd) {
        Pager pager = dao.createPager(curPage, pageSize);
        List<T> list = dao.query(obj, cnd, pager);
        pager.setRecordCount(dao.count(obj, cnd));
        return new QueryResult(list, pager);
    }

    public <T> QueryResult listPage(Dao dao, Class<T> obj, Condition cnd, Pager pager) {
        List<T> list = dao.query(obj, cnd, pager);
        pager.setRecordCount(dao.count(obj, cnd));
        return new QueryResult(list, pager);
    }

    public <T> JSONObject listPageJson(Dao dao, Class<T> obj, int curPage, int pageSize, Condition cnd) {
        JSONObject jsonobj = new JSONObject();
        Pager pager = dao.createPager(curPage, pageSize);
        List<T> list = dao.query(obj, cnd, pager);
        pager.setRecordCount(dao.count(obj, cnd));
        jsonobj.put("total", pager.getRecordCount());
        jsonobj.put("rows", JSONArray.fromObject(list));
        return jsonobj;
    }

    public <T> JSONObject listPageJson(Dao dao, Class<T> obj, Condition cnd, Pager pager) {
        JSONObject jsonobj = new JSONObject();
        List<T> list = dao.query(obj, cnd, pager);
        pager.setRecordCount(dao.count(obj, cnd));
        jsonobj.put("total", pager.getRecordCount());
        jsonobj.put("rows", JSONArray.fromObject(list));
        return jsonobj;
    }

    public <T> QueryResult listPageSql(Dao dao, Sql sql, int curPage, int pageSize) {
        Pager pager = dao.createPager(curPage, pageSize);
        pager.setRecordCount((new Long(Daos.queryCount(dao, sql))).intValue());
        sql.setPager(pager);
        sql.setCallback(Sqls.callback.records());
        dao.execute(sql);
        return new QueryResult(sql.getList(Map.class), pager);
    }

    public <T> QueryResult listPageSql(Dao dao, Sql sql, Pager pager) {
        pager.setRecordCount((new Long(Daos.queryCount(dao, sql))).intValue());
        sql.setPager(pager);
        sql.setCallback(Sqls.callback.records());
        dao.execute(sql);
        return new QueryResult(sql.getList(Map.class), pager);
    }

    public <T> JSONObject listPageJsonSql(Dao dao, Sql sql, int curPage, int pageSize) {
        Pager pager = dao.createPager(curPage, pageSize);
        pager.setRecordCount((new Long(Daos.queryCount(dao, sql))).intValue());
        sql.setPager(pager);
        sql.setCallback(Sqls.callback.records());
        dao.execute(sql);
        JSONObject jsonobj = new JSONObject();
        jsonobj.put("total", pager.getRecordCount());
        jsonobj.put("rows", JSONArray.fromObject(sql.getList(Map.class)));
        return jsonobj;
    }

    public <T> JSONObject listJsonSql(Dao dao, Sql sql) {
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                JSONObject json = new JSONObject();

                while(rs.next()) {
                    String key = StringUtils.null2String(rs.getString(1));
                    String value = StringUtils.null2String(rs.getString(2));
                    json.put(key, value);
                }

                return json;
            }
        });
        dao.execute(sql);
        return (JSONObject)sql.getResult();
    }

    public <T> JSONObject listPageJsonSql(Dao dao, Sql sql, Pager pager) {
        pager.setRecordCount((new Long(Daos.queryCount(dao, sql))).intValue());
        sql.setPager(pager);
        sql.setCallback(Sqls.callback.records());
        dao.execute(sql);
        JSONObject jsonobj = new JSONObject();
        jsonobj.put("total", pager.getRecordCount());
        jsonobj.put("rows", JSONArray.fromObject(sql.getList(Map.class)));
        return jsonobj;
    }

    public <T> String getStrRowValue(Dao dao, Sql sql) {
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                if (rs.next()) {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    return rsmd.getColumnType(1) == 2005 ? StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(1))) : StringUtils.null2String(rs.getString(1));
                } else {
                    return "";
                }
            }
        });
        dao.execute(sql);
        return sql.getString();
    }

    public <T> List<String> getStrRowValues(Dao dao, Sql sql) {
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                List<String> list = new LinkedList();

                for(String value = ""; rs.next(); list.add(value)) {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    if (rsmd.getColumnType(1) == 2005) {
                        value = StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(1)));
                    } else {
                        value = StringUtils.null2String(rs.getString(1));
                    }
                }

                return list;
            }
        });
        dao.execute(sql);
        return sql.getList(String.class);
    }

    public <T> List<List<String>> getMulRowValue(Dao dao, Sql sql) {
        final List<List<String>> value = new ArrayList();
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                ResultSetMetaData rsmd = null;
                if (rs != null) {
                    rsmd = rs.getMetaData();
                    int rowcount = rsmd.getColumnCount();

                    while(rs != null && rs.next()) {
                        List<String> rowvalue = new ArrayList();
                        String temp = "";

                        for(int i = 0; i < rowcount; ++i) {
                            if (rsmd.getColumnTypeName(i + 1).toUpperCase().equals("CLOB")) {
                                temp = StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(i + 1)));
                            } else {
                                temp = StringUtils.null2String(rs.getString(i + 1));
                            }

                            rowvalue.add(temp);
                        }

                        value.add(rowvalue);
                    }
                }

                return null;
            }
        });
        dao.execute(sql);
        return value;
    }

    public <T> List<Hashtable> getMulRowValue(Dao dao, Sql sql, final String[] colname) {
        final List<Hashtable> value = new ArrayList();
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                ResultSetMetaData rsmd = null;
                if (rs != null) {
                    rsmd = rs.getMetaData();
                    int rowcount = rsmd.getColumnCount();
                    String temp;
                    Hashtable htable;
                    int i;
                    if (!"".equals(colname) && rowcount == colname.length) {
                        while(rs != null && rs.next()) {
                            temp = "";
                            htable = new Hashtable();

                            for(i = 0; i < rowcount; ++i) {
                                if (rsmd.getColumnTypeName(i + 1).toUpperCase().equals("CLOB")) {
                                    temp = StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(i + 1)));
                                } else {
                                    temp = StringUtils.null2String(rs.getString(i + 1));
                                }

                                htable.put(colname[i], temp);
                            }

                            value.add(htable);
                        }
                    } else if (colname.length != rowcount - 1) {
                        LOGGER.info("错误:listPageJsonSql(datasource,sql,colname) 查询语句字段数与绑定字段数不一致");
                    } else {
                        while(rs != null && rs.next()) {
                            temp = "";
                            htable = new Hashtable();

                            for(i = 0; i < rowcount; ++i) {
                                if (rsmd.getColumnTypeName(i + 1).toUpperCase().equals("CLOB")) {
                                    temp = StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(i + 1)));
                                } else {
                                    temp = StringUtils.null2String(rs.getString(i + 1));
                                }

                                if (i == rowcount - 1) {
                                    htable.put("rowid", temp);
                                } else {
                                    htable.put(colname[i], temp);
                                }
                            }

                            value.add(htable);
                        }
                    }
                }

                return null;
            }
        });
        dao.execute(sql);
        return value;
    }

    public <T> String getSubMenuId(Dao dao, String tableName, String cloName, final String value) {
        Sql sql = Sqls.create("select " + cloName + " from " + tableName + " where " + cloName + " like '" + value + "____' order by " + cloName + " desc");
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                String rsvalue = value + "0001";
                if (rs != null && rs.next()) {
                    rsvalue = rs.getString(1);
                    int newvalue = Integer.parseInt(rsvalue.substring(rsvalue.length() - 4)) + 1;
                    rsvalue = rsvalue.substring(0, rsvalue.length() - 4) + (new DecimalFormat("0000")).format((long)newvalue);
                }

                return rsvalue;
            }
        });
        dao.execute(sql);
        return sql.getString();
    }

    public <T> String getSubMenuId(Dao dao, String tableName, String cloName, final String value, String wheresql) {
        Sql sql = Sqls.create("select " + cloName + " from " + tableName + " where " + cloName + " like '" + value + "____' " + wheresql + " order by " + cloName + " desc");
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                String rsvalue = value + "0001";
                if (rs != null && rs.next()) {
                    rsvalue = rs.getString(1);
                    int newvalue = Integer.parseInt(rsvalue.substring(rsvalue.length() - 4)) + 1;
                    rsvalue = rsvalue.substring(0, rsvalue.length() - 4) + (new DecimalFormat("0000")).format((long)newvalue);
                }

                return rsvalue;
            }
        });
        dao.execute(sql);
        return sql.getString();
    }

    public <T> Hashtable<String, String> getHTable(Dao dao, Sql sql) {
        final Hashtable<String, String> htable = new Hashtable();
        sql.setCallback(new SqlCallback() {
            @Override
            public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
                String key = "";

                for(String value = ""; rs.next(); htable.put(key, value)) {
                    ResultSetMetaData rsmd = rs.getMetaData();
                    if (rsmd.getColumnType(1) == 2005) {
                        key = StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(1)));
                    } else {
                        key = StringUtils.null2String(rs.getString(1));
                    }

                    if (rsmd.getColumnType(2) == 2005) {
                        value = StringUtils.null2String(DBObject.getClobBody(rs, rsmd.getColumnName(2)));
                    } else {
                        value = StringUtils.null2String(rs.getString(2));
                    }
                }

                return null;
            }
        });
        dao.execute(sql);
        return htable;
    }
}
